from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.http import require_http_methods

from tetor import models
import torch
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Create your views here.

class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x):
        y_pred = self.linear(x)
        return y_pred


class LoadModel:
    def __init__(self):
        file_name = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'model/m2.pth')
        self.model = LinearModel()
        self.model.load_state_dict(torch.load(file_name))

    def predict(self, num: float) -> float:
        x1 = [num]
        x2 = [x1]
        pre_x = torch.tensor(x2)
        pred_y = self.model(pre_x)
        return pred_y.detach().numpy()[0][0]


def add_f_view(request):
    path = os.path.abspath(os.path.dirname(__file__))

    return render(request, 'sendAjax.html', context={'path': str(path)})


@require_http_methods(["GET", "POST"])
def make_model(request):
    """
    :param request:
    :return: HttpResponse TO show that the model has been loaded.

    This function must be called before calling function pred.
    """
    # if not my_model:
    #     global my_model
    #     my_model=LoadModel()
    #
    #
    #     return
    # else:
    #     return
    global my_model
    my_model = LoadModel()
    return HttpResponse('Model has been loaded successfully!')


def test_show_data(request):
    mess = models.People.objects.all()

    return render(request, 'tshow.html', context={'peos': mess})


@require_http_methods(["GET", "POST"])
def pred(request, num):
    """

    :param request:
    :param num: the number to be predicted
    :return: HttpResponse with a predicted number
    """
    # model=LoadModel()

    # try:
    #     y=my_model.predict(float(num))
    # except NameError as e:
    #     make_model(request=None)
    y = my_model.predict(float(num))
    return HttpResponse(str(y))
